package com.youku.api;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.lang3.StringUtils;

import com.youku.exception.AssertException;
import com.youku.util.ReflectHelper;

public class ApiCaller {
	
	public static Object call(String methodName, String invokeMethodFormatter, Object... args) {
		Invoker invoker = ReflectHelper.newInstance(Invoker.class, new Class<?>[] { String.class },
				new String[] { invokeMethodFormatter });

		Class<?>[] argTypes = null;
		Object[] arguments = null;
		if (hasArrayArgs(methodName)) {
			argTypes = new Class[] { Object[].class };
			arguments = new Object[] { args };
		} else {
			argTypes = new Class[args.length];
			for (int i = 0; i < argTypes.length; i++) {
				argTypes[i] = Object.class;
			}
			arguments = args;
		}

		try {
			Method method = Invoker.class.getDeclaredMethod(methodName, argTypes);
			return method.invoke(invoker, arguments);
		} catch (Exception e) {
			if (e instanceof InvocationTargetException) {
				String message = ((InvocationTargetException) e).getTargetException().getMessage();

				throw new AssertException(message);
			} else {
				throw new RuntimeException(e);
			}
		}

	}

	private static boolean hasArrayArgs(String methodName) {
		if (StringUtils.isBlank(methodName))
			return false;
		for (Method method : Invoker.class.getDeclaredMethods()) {
			if(methodName.equals(method.getName())){
				for (Class<?> argClass : method.getParameterTypes()) {
					if (argClass.isArray()) {
						return true;
					}
				}
			}
		}
		return false;
	}

	public static void main(String[] args) throws NoSuchMethodException, SecurityException {
		try {
			System.out.println(call("join", "kkkkkkkk", "ab", "cc",11, "ddd", "efasdf"));
		} catch (AssertException e) {
			e.printStackTrace();
		}
	}

}
